import 'dart:convert';
import 'dart:math';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:situation/data/channel/intercom_channel.dart';
import 'package:situation/data/store/auth_store.dart';
import 'package:situation/data/store/im_store.dart';


class UtilMqtt {

  connect() async {


    String userId = AuthStore.to.profile.id!;

    String server = "192.168.1.23";
    int port = 1883;
    String clientId = "";
    String userName = "${userId}_android_" + randomString(8);
    String password = "${userId}_android_" + randomString(8);
    ImStore.getInstance()
        .connect(server, port, clientId, userName, password)
        .then((v) {
      if (v!.returnCode == MqttConnectReturnCode.connectionAccepted) {
        print("恭喜你~ ====mqtt连接成功");
        ImStore.getInstance().subscribeMessage("bdjw-common-topic");
        ImStore.getInstance()
            .subscribeMessage("bdjw-user-topic-${userId}_uniapp");

        ImStore.getInstance()
            .updates()!
            .listen((List<MqttReceivedMessage<MqttMessage>> data) async {
          final recMess = data[0].payload as MqttPublishMessage;
          final topic = data[0].topic;

          final String pt = Utf8Decoder().convert(recMess.payload.message);
          print(
              'BDJWMQTT::Change notification:: topic is <${data[0].topic}>, payload is <-- $pt -->');
          var jsonObject = json.decode(pt);


          if (jsonObject['event'] == 'invite_to_room') {
            // 启动视频或者音频
            if (jsonObject['type'] == 'video') {
              // 将APP 唤醒
              // Get.toNamed(RouterName.imVideoChat, arguments: params);
              jsonObject['event'] = "bdjwCall";
              jsonObject['myId'] = userId;
              jsonObject['myName'] = AuthStore.to.profile.username;

              IntercomChannel.to.sendMsg(jsonObject);
            }
          }

          // 消息操作
        });
      } else if (v.returnCode == MqttConnectReturnCode.badUsernameOrPassword) {
        print("有事做了~ ====mqtt连接失败 --密码错误!!!");
      } else {
        print("有事做了~ ====mqtt连接失败!!!");
      }
    });
  }

  // 随机数
  randomString(int length) {
    const chars =
        'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890';
    return List.generate(
        length, (index) => chars[Random().nextInt(chars.length)]).join();
  }


  // 断开链接
  disconnect() {
    ImStore.getInstance().disconnect();
  }
}
